// pages/order_create/index.js
const MoneyUtils = require('../../utils/money.js')

Page({
  data: {
    navBarHeight: 0,
    contentTop: 0,
    bottomSafeArea: 0,
    fromCart: false, // 是否来自购物车
    
    // 订单商品信息
    orderItems: [],
    
    // 地址信息
    selectedAddress: null,
    
    // 订单金额信息
    totalAmount: 0,
    discountAmount: 0,
    actualAmount: 0,
    totalAmountFormatted: '0.00',
    discountAmountFormatted: '0.00',
    actualAmountFormatted: '0.00',
    
    // 支付方式
    paymentMethods: [
      { id: 'balance', name: '余额支付', icon: '/images/icons/wechat-pay.png', enabled: false, amount: 0, amountFormatted: '0.00' },
      { id: 'wechat', name: '微信支付', icon: '/images/icons/wechat.png', enabled: false, amount: 0, amountFormatted: '0.00' },
      { id: 'combo', name: '组合支付', icon: '/images/icons/combo-pay.png', enabled: false, amount: 0, amountFormatted: '0.00', balanceAmount: 0, wechatAmount: 0 },
      { id: 'alipay', name: '支付宝', icon: '/images/icons/wechat-pay.png', enabled: false, amount: 0, amountFormatted: '0.00' },
      { id: 'bank', name: '银行卡', icon: '/images/icons/wechat-pay.png', enabled: false, amount: 0, amountFormatted: '0.00' }
    ],
    
    // 用户信息
    userInfo: null,
    userBalance: 0,
    userBalanceFormatted: '0.00',
    
    // 订单备注
    orderNote: '',
    
    // 提交状态
    submitting: false,
    
    // 支付密码相关
    showPasswordModal: false,
    paymentPassword: '',
    pendingOrderData: null
  },

  onLoad(options) {
    // 计算导航栏高度和底部安全区域
    const systemInfo = wx.getSystemInfoSync()
    const statusBarHeight = systemInfo.statusBarHeight
    const navBarHeight = statusBarHeight + 44
    const bottomSafeArea = systemInfo.safeArea ? systemInfo.screenHeight - systemInfo.safeArea.bottom : 0
    
    this.setData({
      navBarHeight,
      contentTop: navBarHeight,
      bottomSafeArea,
      fromCart: options.fromCart === 'true' // 标记是否来自购物车
    })
    
    // 获取订单商品信息
    if (options.orderData) {
      try {
        const orderItems = JSON.parse(decodeURIComponent(options.orderData))
        this.setData({ orderItems })
        this.calculateAmount()
      } catch (error) {
        console.error('解析订单数据失败:', error)
        wx.showToast({
          title: '订单数据错误',
          icon: 'none'
        })
        setTimeout(() => {
          wx.navigateBack()
        }, 1500)
      }
    }
    
    // 加载用户信息和地址
    this.loadUserInfo()
    this.loadDefaultAddress()
  },

  // 加载用户信息
  async loadUserInfo() {
    try {
      const result = await wx.cloud.callFunction({
        name: 'getUserInfo'
      })
      
      if (result.result.success) {
        const userInfo = result.result.data
        const balance = MoneyUtils.formatAmount(userInfo.balance || 0)
        this.setData({
          userInfo,
          userBalance: balance,
          userBalanceFormatted: MoneyUtils.formatAmount(balance).toFixed(2)
        })
        
        // 更新余额支付方式的可用金额
        const paymentMethods = this.data.paymentMethods.map(method => {
          if (method.id === 'balance') {
            return { ...method, amount: MoneyUtils.formatAmount(balance) }
          }
          return method
        })
        this.setData({ paymentMethods })
      }
    } catch (error) {
      console.error('获取用户信息失败:', error)
    }
  },

  // 加载默认地址
  async loadDefaultAddress() {
    try {
      // 优先从本地缓存加载默认地址
      const cachedAddress = wx.getStorageSync('defaultAddress')
      if (cachedAddress) {
        this.setData({
          selectedAddress: cachedAddress
        })
        return
      }
      
      // 本地无缓存，从云端获取
      const result = await wx.cloud.callFunction({
        name: 'getAddressList'
      })
      
      if (result.result.success) {
        const defaultAddress = result.result.data.find(addr => addr.isDefault)
        if (defaultAddress) {
          this.setData({
            selectedAddress: defaultAddress
          })
          // 更新本地缓存
          wx.setStorageSync('defaultAddress', defaultAddress)
          wx.setStorageSync('addressCacheTime', Date.now())
        }
      }
    } catch (error) {
      console.error('获取默认地址失败:', error)
    }
  },

  // 计算订单金额
  calculateAmount() {
    const { orderItems } = this.data
    let totalAmount = 0
    
    // 计算每个商品的小计并更新商品数据
    const updatedOrderItems = orderItems.map(item => {
      // 使用包含规格偏移的价格进行计算，确保金额精度
      const itemPrice = MoneyUtils.formatAmount(item.price || item.basePrice || 0)
      const subtotal = MoneyUtils.multiply(itemPrice, item.quantity)
      totalAmount = MoneyUtils.add(totalAmount, subtotal)
      
      // 计算价格偏移量
      let priceOffsetFormatted = ''
      let discountAmountFormatted = ''
      if (item.basePrice && MoneyUtils.compare(itemPrice, item.basePrice) !== 0) {
        const priceDiff = MoneyUtils.formatAmount(Math.abs(itemPrice - item.basePrice))
        if (MoneyUtils.compare(itemPrice, item.basePrice) > 0) {
          priceOffsetFormatted = MoneyUtils.formatAmount(priceDiff).toFixed(2)
        } else {
          discountAmountFormatted = MoneyUtils.formatAmount(priceDiff).toFixed(2)
        }
      }
      
      return {
        ...item,
        price: itemPrice, // 确保使用正确的价格
        subtotal: MoneyUtils.formatAmount(subtotal).toFixed(2),
        priceFormatted: MoneyUtils.formatAmount(itemPrice).toFixed(2),
        priceOffsetFormatted,
        discountAmountFormatted
      }
    })
    
    // 暂时不计算优惠
    const discountAmount = 0
    const actualAmount = MoneyUtils.subtract(totalAmount, discountAmount)
    
    this.setData({
      orderItems: updatedOrderItems,
      totalAmount: MoneyUtils.formatAmount(totalAmount),
      discountAmount: MoneyUtils.formatAmount(discountAmount),
      actualAmount: MoneyUtils.formatAmount(actualAmount),
      totalAmountFormatted: MoneyUtils.formatAmount(totalAmount).toFixed(2),
      discountAmountFormatted: MoneyUtils.formatAmount(discountAmount).toFixed(2),
      actualAmountFormatted: MoneyUtils.formatAmount(actualAmount).toFixed(2)
    })
  },

  // 选择地址
  selectAddress() {
    const selectedId = this.data.selectedAddress ? this.data.selectedAddress._id : ''
    wx.navigateTo({
      url: `/pages/address_list/index?mode=select&selectedId=${selectedId}`
    })
  },

  // 切换支付方式
  togglePaymentMethod(e) {
    const methodId = e.currentTarget.dataset.id
    
    // 如果不是余额支付、微信支付和组合支付，显示未开通提示
    if (methodId !== 'balance' && methodId !== 'wechat' && methodId !== 'combo') {
      wx.showToast({
        title: '该支付方式暂未开通',
        icon: 'none',
        duration: 2000
      })
      return
    }
    
    // 检查组合支付的可用性
    if (methodId === 'combo') {
      const { userBalance, actualAmount } = this.data
      if (userBalance === 0 || userBalance >= actualAmount) {
        wx.showToast({
          title: userBalance === 0 ? '余额为0，无法使用组合支付' : '余额充足，请直接使用余额支付',
          icon: 'none',
          duration: 2000
        })
        return
      }
    }
    
    // 单选逻辑：选择一种支付方式时，取消其他方式
    const paymentMethods = this.data.paymentMethods.map(method => {
      if (method.id === methodId) {
        return { ...method, enabled: !method.enabled }
      } else {
        return { ...method, enabled: false }
      }
    })
    
    this.setData({ paymentMethods })
    this.calculatePaymentAmount()
  },

  // 计算各支付方式金额
  calculatePaymentAmount() {
    const { paymentMethods, actualAmount, userBalance } = this.data
    const enabledMethods = paymentMethods.filter(method => method.enabled)
    
    if (enabledMethods.length === 0) return
    
    // 重置所有金额
    let updatedMethods = paymentMethods.map(method => ({ 
      ...method, 
      amount: 0,
      amountFormatted: '0.00',
      balanceAmount: 0,
      wechatAmount: 0
    }))
    
    const enabledMethod = enabledMethods[0] // 单选，只有一个启用的方法
    
    if (enabledMethod.id === 'balance') {
      // 纯余额支付
      const balanceMethod = updatedMethods.find(method => method.id === 'balance')
      if (MoneyUtils.compare(userBalance, actualAmount) >= 0) {
        balanceMethod.amount = MoneyUtils.formatAmount(actualAmount)
        balanceMethod.amountFormatted = MoneyUtils.formatAmount(actualAmount).toFixed(2)
      } else {
        // 余额不足，使用全部余额
        balanceMethod.amount = MoneyUtils.formatAmount(userBalance)
        balanceMethod.amountFormatted = MoneyUtils.formatAmount(userBalance).toFixed(2)
      }
    } else if (enabledMethod.id === 'wechat') {
      // 纯微信支付
      const wechatMethod = updatedMethods.find(method => method.id === 'wechat')
      wechatMethod.amount = MoneyUtils.formatAmount(actualAmount)
      wechatMethod.amountFormatted = MoneyUtils.formatAmount(actualAmount).toFixed(2)
    } else if (enabledMethod.id === 'combo') {
      // 组合支付：余额 + 微信支付
      const comboMethod = updatedMethods.find(method => method.id === 'combo')
      const balanceAmount = MoneyUtils.formatAmount(Math.min(userBalance, actualAmount))
      const wechatAmount = MoneyUtils.subtract(actualAmount, balanceAmount)
      
      comboMethod.amount = MoneyUtils.formatAmount(actualAmount)
      comboMethod.amountFormatted = MoneyUtils.formatAmount(actualAmount).toFixed(2)
      comboMethod.balanceAmount = MoneyUtils.formatAmount(balanceAmount)
      comboMethod.wechatAmount = MoneyUtils.formatAmount(wechatAmount)
    }
    
    this.setData({ paymentMethods: updatedMethods })
  },

  // 输入订单备注
  onNoteInput(e) {
    this.setData({
      orderNote: e.detail.value
    })
  },

  // 计算商品规格价格偏移
  calculateSpecOffset(item) {
    if (!item.selectedSpec || !item.specifications) {
      return 0
    }

    let totalOffset = 0
    
    // 如果商品数据中包含规格信息，计算偏移量
    if (item.specifications && Array.isArray(item.specifications)) {
      item.specifications.forEach(spec => {
        if (spec.offset && item.selectedSpec[spec.name]) {
          const selectedOptionName = item.selectedSpec[spec.name].name || item.selectedSpec[spec.name]
          const optionIndex = spec.options.findIndex(option => 
            (typeof option === 'string' ? option : option.name) === selectedOptionName
          )
          
          if (optionIndex !== -1 && spec.offset[optionIndex] !== undefined) {
            totalOffset += spec.offset[optionIndex]
          }
        }
      })
    }

    return parseFloat(totalOffset.toFixed(2))
  },

  // 提交订单
  async submitOrder() {
    if (this.data.submitting) return
    
    // 验证必要信息
    if (!this.data.selectedAddress) {
      wx.showToast({
        title: '请选择收货地址',
        icon: 'none'
      })
      return
    }
    
    const enabledPayments = this.data.paymentMethods.filter(method => method.enabled && method.amount > 0)
    if (enabledPayments.length === 0) {
      wx.showToast({
        title: '请选择支付方式',
        icon: 'none'
      })
      return
    }
    
    // 验证支付金额
    const totalPaymentAmount = enabledPayments.reduce((sum, method) => MoneyUtils.add(sum, method.amount), 0)
    if (MoneyUtils.compare(totalPaymentAmount, this.data.actualAmount) !== 0) {
      wx.showToast({
        title: '支付金额不匹配',
        icon: 'none'
      })
      return
    }
    
    // 验证余额支付
    const balancePayment = enabledPayments.find(method => method.id === 'balance')
    const comboPayment = enabledPayments.find(method => method.id === 'combo')
    
    if (balancePayment && MoneyUtils.compare(balancePayment.amount, this.data.userBalance) > 0) {
      wx.showToast({
        title: '余额不足',
        icon: 'none'
      })
      return
    }
    
    // 检查是否需要支付密码验证
    const needPasswordVerify = (balancePayment && balancePayment.amount > 0) || 
                              (comboPayment && comboPayment.balanceAmount > 0)
    
    if (needPasswordVerify) {
      // 需要支付密码验证，显示密码输入框
      const orderData = {
        addressId: this.data.selectedAddress._id,
        totalAmount: this.data.totalAmount,
        actualAmount: this.data.actualAmount,
        discountAmount: this.data.discountAmount,
        items: this.data.orderItems.map(item => ({
          ...item,
          basePrice: item.basePrice || item.price,
          finalPrice: item.price,
          specOffset: this.calculateSpecOffset(item)
        })),
        paymentMethods: enabledPayments,
        notes: this.data.orderNote
      }
      
      this.setData({
        pendingOrderData: orderData,
        showPasswordModal: true
      })
      return
    }
    
    // 不需要密码验证，直接提交订单
    await this.doSubmitOrder()
  },

  // 实际提交订单
  async doSubmitOrder(paymentPassword = null) {
    if (this.data.submitting) return
    
    this.setData({ submitting: true })
    
    try {
      wx.showLoading({
        title: '提交订单中...',
        mask: true
      })
      
      // 使用待提交的订单数据或重新构建
      const orderData = this.data.pendingOrderData || {
        addressId: this.data.selectedAddress._id,
        totalAmount: this.data.totalAmount,
        actualAmount: this.data.actualAmount,
        discountAmount: this.data.discountAmount,
        items: this.data.orderItems.map(item => ({
          ...item,
          basePrice: item.basePrice || item.price,
          finalPrice: item.price,
          specOffset: this.calculateSpecOffset(item)
        })),
        paymentMethods: this.data.paymentMethods.filter(method => method.enabled && method.amount > 0),
        notes: this.data.orderNote
      }
      
      // 如果有支付密码，添加到订单数据中
      if (paymentPassword) {
        orderData.paymentPassword = paymentPassword
      }
      
      // 调用云函数创建订单
      // 调用云函数创建订单
      const result = await wx.cloud.callFunction({
        name: 'createOrder',
        data: orderData
      })
      
      if (result.result.success) {
        // 如果是微信支付或组合支付，调用微信支付
        if (result.result.paymentType === 'wechat' || result.result.paymentType === 'combo') {
          await this.handleWechatPay(result.result)
        } else {
          // 余额支付成功
          await this.handlePaymentSuccess(result.result)
        }
      } else {
        // 处理特殊错误情况
        if (result.result.needSetPassword) {
          wx.hideLoading()
          this.handleNeedSetPassword()
          return
        } else if (result.result.needPassword) {
          wx.hideLoading()
          wx.showToast({
            title: '请输入支付密码',
            icon: 'none'
          })
          return
        } else {
          throw new Error(result.result.message || '订单提交失败')
        }
      }
    } catch (error) {
      console.error('提交订单失败:', error)
      wx.hideLoading()
      wx.showToast({
        title: error.message || '订单提交失败',
        icon: 'none'
      })
    } finally {
      this.setData({ 
        submitting: false,
        pendingOrderData: null
      })
    }
  },

  // 处理需要设置支付密码的情况
  handleNeedSetPassword() {
    wx.hideLoading()
    wx.showModal({
      title: '提示',
      content: '您还未设置支付密码，是否立即设置？',
      confirmText: '立即设置',
      cancelText: '取消',
      success: (res) => {
        if (res.confirm) {
          wx.navigateTo({
            url: '/pages/payment_password_set/index?mode=set'
          })
        }
      }
    })
  },

  // 支付密码验证成功
  onPasswordSuccess(e) {
    const { password } = e.detail
    this.setData({
      showPasswordModal: false,
      paymentPassword: password
    })
    
    // 使用验证成功的密码提交订单
    this.doSubmitOrder(password)
  },

  // 关闭密码输入框
  onPasswordClose() {
    this.setData({
      showPasswordModal: false,
      pendingOrderData: null
    })
  },

  // 忘记密码
  onPasswordForget() {
    this.setData({
      showPasswordModal: false
    })
    
    wx.showModal({
      title: '忘记密码',
      content: '是否重置支付密码？',
      confirmText: '立即重置',
      cancelText: '取消',
      success: (res) => {
        if (res.confirm) {
          wx.navigateTo({
            url: '/pages/payment_password_reset/index'
          })
        }
      }
    })
  },

  // 设置支付密码
  // 设置支付密码
  // 设置支付密码
  async onPasswordSet() {
    // 先检查用户是否真的未设置密码
    try {
      wx.showLoading({
        title: '检查中...',
        mask: true
      })

      const result = await wx.cloud.callFunction({
        name: 'verifyPaymentPassword',
        data: {
          checkOnly: true
        }
      })

      wx.hideLoading()

      if (result.result.code === 'NO_PASSWORD_SET') {
        // 确实未设置密码，允许跳转到设置页面
        this.setData({
          showPasswordModal: false
        })
        
        wx.navigateTo({
          url: '/pages/payment_password_reset/index?skipOldPassword=true'
        })
      } else {
        // 已设置密码，不允许跳过验证
        wx.showModal({
          title: '安全提示',
          content: '检测到您已设置支付密码，请输入密码进行验证。如忘记密码，请点击"忘记密码？"进行重置。',
          showCancel: false,
          confirmText: '知道了'
        })
      }
    } catch (error) {
      wx.hideLoading()
      console.error('检查密码状态失败:', error)
      wx.showToast({
        title: '检查失败，请重试',
        icon: 'none'
      })
    }
  },

  // 处理微信支付
  async handleWechatPay(orderResult) {
    try {
      // 从云开发返回的payment对象中获取支付参数
      const paymentParams = orderResult.payment
      
      // 调用微信支付
      await wx.requestPayment({
        timeStamp: paymentParams.timeStamp,
        nonceStr: paymentParams.nonceStr,
        package: paymentParams.package,
        signType: paymentParams.signType,
        paySign: paymentParams.paySign
      })
      
      // 支付成功
      await this.handlePaymentSuccess(orderResult)
    } catch (payError) {
      wx.hideLoading()
      if (payError.errMsg === 'requestPayment:fail cancel') {
        wx.showToast({
          title: '支付已取消',
          icon: 'none'
        })
      } else {
        wx.showToast({
          title: '支付失败，请重试',
          icon: 'none'
        })
      }
      console.error('微信支付失败:', payError)
    }
  },

  // 处理支付成功
  async handlePaymentSuccess(orderResult) {
    // 如果是从购物车来的订单，需要清理购物车中的商品
    if (this.data.fromCart) {
      await this.clearCartItems()
    }
    
    wx.hideLoading()
    wx.showToast({
      title: '订单提交成功',
      icon: 'success'
    })
    
    // 跳转到订单详情页面
    setTimeout(() => {
      wx.redirectTo({
        url: `/pages/order_detail/index?orderId=${orderResult.orderId}`
      })
    }, 1500)
  },

  // 清理购物车中已下单的商品
  async clearCartItems() {
    try {
      const cartItemIds = this.data.orderItems
        .filter(item => item.cartItemId)
        .map(item => item.cartItemId)
      
      if (cartItemIds.length > 0) {
        await wx.cloud.callFunction({
          name: 'batchRemoveCartItems',
          data: {
            itemIds: cartItemIds
          }
        })
        console.log('购物车商品清理成功')
      }
    } catch (error) {
      console.error('清理购物车商品失败:', error)
      // 不影响订单提交，只记录错误
    }
  },

  // 返回按钮
  handleBack() {
    wx.navigateBack()
  }
})